#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/8/16'
"""
import talib

from py_at.Enums import *
from py_at.Data import Data
import numpy as np
import talib as ta
import time
from py_at.strategy import Strategy
class TuPoHL(Strategy):
    def __init__(self,cfg):
        super().__init__(cfg)
        # 初始化默认参数
        if cfg =="":
            self.Params['Hlengh'] = 50
            self.Params['llengh'] = 50
            self.Params['Lots'] = 25
            self.Params['Slippage']=1

        self.Slippage = self.Params['Slippage']
        self.p_lots = self.Params['Lots']
        self.p_llengh = self.Params['llengh']
        self.p_Hlengh = self.Params['Hlengh']
        self.Ticks=np.array([])
        self.TickBarPrice =np.array([])
        self.TickBarDate = np.array([])


    def on_tick(self,tick):
        #print('长度%s  当前tick%s' %(len(self.Ticks),tick))

        self.Ticks = np.append(self.Ticks, tick)
        self.TickBarPrice = np.append(self.TickBarPrice,tick.LastPrice)
        self.TickBarDate = np.append(self.TickBarDate,tick.UpdateTime)
        self.O=self.C=self.L=self.H=np.append(self.O,tick.LastPrice)
        self.D = np.append(self.D, tick.UpdateTime.strftime("%Y%m%d %H:%M:%S"))
        if(len(self.Ticks)<self.p_llengh+1):
            return
        # if len(self.Ticks) > max(self.p_Hlengh, self.p_llengh):
        #     self.Ticks = np.delete(self.Ticks, 0)
        # if len(self.TickBarPrice) > max(self.p_Hlengh, self.p_llengh):
        #     self.TickBarPrice = np.delete(self.TickBarPrice, 0)
        # if len(self.TickBarDate) > max(self.p_Hlengh, self.p_llengh):
        #     self.TickBarDate = np.delete(self.TickBarDate, 0)

        avgMa1=ta.MA(self.TickBarPrice,self.p_Hlengh)

        #if(self.timeD!=self.D[-1]):
            # self.writeStrategyLog("时间{0}开{1} 高{2} 低{3} 收{4}合约{5}".format(self.D[-2],self.O[-2],self.H[-2],self.L[-2],self.C[-2],self.Instrument))
            # self.writeStrategyLog("开%s 高%s 低%s 收%s 时间%s bar 合约%s" % (self.Bars[-2].O, self.Bars[-2].H, self.Bars[-2].L, self.Bars[-2].C, self.D[-2],self.Instrument))
            # self.writeStrategyLog("ID%s上根时间|%s时间ma均线%s ma2均线%s 合约%s" % (self.ID,self.D[-2], ma1[-2], ma2[-2],self.Instrument))
            #self.writeStrategyLog("ID%s当前多仓%s当前空仓%s" % (self.ID,self.PositionLong, self.PositionShort))
        self.Varlist['ma'] = avgMa1.tolist()
        self.Varlist['tick'] = self.TickBarPrice.tolist()
        up=self.TickBarPrice[-2]>avgMa1[-2] and self.TickBarPrice[-3]>avgMa1[-3] and self.TickBarPrice[-4]>avgMa1[-4] and self.TickBarPrice[-11]>avgMa1[-11]
        down = self.TickBarPrice[-2]<avgMa1[-2] and self.TickBarPrice[-3]<avgMa1[-3] and self.TickBarPrice[-4]<avgMa1[-4] and self.TickBarPrice[-11]<avgMa1[-11]
        if(up and self.PositionLong!=1):
            self.Buy(tick.LastPrice,1,"买开")
        if(down and self.PositionLong==1):
            self.Sell(tick.LastPrice,1,"卖平")
        if(down and self.PositionShort!=1):
            self.SellShort(tick.LastPrice,1,"卖开")
        if(up and self.PositionShort==1):
            self.BuyToCover(tick.LastPrice,1,"买平")


    # def BarUpdate(self):
    #
    #     # print('时间{0}收盘价格{1}总k线数据'.format(self.D, self.C, len(self.C)))
    #     # if len(self.C) == 1:       # 第一根bar
    #     #     self.UpdateParams()
    #
    #     if len(self.C) < self.p_Hlengh:     # 如果bar数目小于 p._ma2参数  退出
    #         return
    #
    #     ma1 = talib.MA(self.H, self.p_ma1)
    #     ma2 = talib.MA(self.L, self.p_ma2)
    #     if(self.timeD!=self.D[-1]):
    #         # self.writeStrategyLog("时间{0}开{1} 高{2} 低{3} 收{4}合约{5}".format(self.D[-2],self.O[-2],self.H[-2],self.L[-2],self.C[-2],self.Instrument))
    #         # self.writeStrategyLog("开%s 高%s 低%s 收%s 时间%s bar 合约%s" % (self.Bars[-2].O, self.Bars[-2].H, self.Bars[-2].L, self.Bars[-2].C, self.D[-2],self.Instrument))
    #         # self.writeStrategyLog("ID%s上根时间|%s时间ma均线%s ma2均线%s 合约%s" % (self.ID,self.D[-2], ma1[-2], ma2[-2],self.Instrument))
    #         #self.writeStrategyLog("ID%s当前多仓%s当前空仓%s" % (self.ID,self.PositionLong, self.PositionShort))
    #
    #         self.timeD = self.D[-1]
    #         # highest = self.H[-self.p_ma1*-1:-1].max()
    #         # lowest=self.L[-self.p_ma1*-1:-1].min()
    #         self.Varlist['Hma'] = ma1.tolist()
    #         self.Varlist['Lma'] = ma2.tolist()
    #     if self.PositionLong == 0:    # 多仓等于0  上传
    #         if self.C[-2]>ma1[-2] and self.C[-3]>ma1[-3] and self.C[-4]>ma1[-4] and self.C[-5]>ma1[-5] :
    #             #self.writeStrategyLog("已经上传 %s"  %self.timeD);
    #             if self.PositionShort > 0:     # 如果有空仓
    #                 #self.writeStrategyLog("当前仓位为-1所以先平掉 买平");
    #                 self.BuyToCover(self.O[-1]+self.Slippage*self.PriceTick, self.p_lots, '买平')  # 平空 当前k收盘
    #             self.Buy(self.O[-1]+self.Slippage*self.PriceTick, self.p_lots, '买开')     # 买多
    #             self.writeStrategyLog("{0}开盘价格{1}开多 加上滑点为{2}".format(self.D[-1],self.O[-1],self.O[-1]+self.Slippage*self.PriceTick))
    #     elif self.PositionShort == 0:
    #         if self.C[-2]<ma2[-2] and self.C[-3]<ma2[-3] and self.C[-4]<ma2[-4] and self.C[-5]<ma2[-5]  :
    #             #self.writeStrategyLog("已经下传 %s" %self.timeD);
    #             if self.PositionLong > 0:
    #                 #self.writeStrategyLog("当前仓位为1所以先平掉 卖平");
    #                 self.Sell(self.O[-1]-self.Slippage*self.PriceTick, self.p_lots, '卖平')
    #             self.SellShort(self.O[-1]-self.Slippage*self.PriceTick, self.p_lots, '卖开')
    #             self.writeStrategyLog("{0}开盘价格{1}开空 加上滑点为{2}".format(self.D[-1], self.O[-1],self.O[-1]-self.Slippage*self.PriceTick))

